//202302104036崔晓涵
package cn.edu.sdjzu.xg.eagle.controller;

import cn.edu.sdjzu.xg.eagle.entity.Student;
import cn.edu.sdjzu.xg.eagle.factory.ServiceFactory;
import cn.edu.sdjzu.xg.eagle.service.StudentService;
import cn.edu.sdjzu.xg.eagle.util.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet({"/studentModification/*", "/studentModification"})
public class StudentModificationCtrl extends HttpServlet {

    private StudentService studentService = null;
    @Override
    public void init() throws ServletException {
        studentService = ServiceFactory.getService(StudentService.class, "StudentServiceImpl");
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //根据request对象，获得代表参数的JSON字串
        String student_json = JSONUtil.getJSON(request);
        //将JSON字串解析为Teacher对象
        Student studentToAdd = JSON.parseObject(student_json, Student.class);

        //创建JSON对象message，以便往前端响应信息
        JSONObject msg = new JSONObject();
        //在数据库表中增加Teacher对象
        try {
            studentService.add(studentToAdd);
            msg.put("msg", "增加成功");
            msg.put("code","200");
            //log.error("成功！:");
        }catch (SQLException e){
            msg.put("msg", "数据库操作异常");
            msg.put("code","500");
            e.printStackTrace();
            // 记录SQLException的错误信息
            //log.error("数据库操作异常: {}", e.getMessage(), e);
        }catch(Exception e){
            msg.put("msg", "网络异常");
            msg.put("code","500");
            e.printStackTrace();
            // 记录其它的错误信息
            //log.error("网络异常: {}", e.getMessage(), e);
        }
        //响应message到前端
        response.getWriter().println(JSON.toJSONString(msg));

    }

}
